﻿using System;
using System.Net;
using System.Data;
using System.Drawing;
using System.Windows.Forms;
using System.Threading;
using System.Collections;
using HSIA.SMS;

namespace HSIA
{
    public partial class FrmMain : Form
    {
        public FrmMain()
        {
            InitializeComponent();
            Control.CheckForIllegalCrossThreadCalls = false;
        }
        public const int WM_DISTURB = 0x0407;

        protected override void DefWndProc(ref Message m)
        {
            switch (m.Msg)
            {
                case PC.WM_Received:
                    if (m.LParam.ToInt32() == 100) tmWait.Enabled = true;
                    else if (m.LParam.ToInt32() == 200)
                    {
                        htNetOrderList2.Remove(sLastCOMID);
                        htNetOrderList3.Remove(sLastCOMID);
                    }
                    //SendToCOM(80);
                    break;

                case WM_DISTURB:
                    tmWait.Enabled = false;
                    break;

                case PC.WM_GatherData:
                    int iReceiverId = m.WParam.ToInt32();
                    int iType = m.LParam.ToInt32();
                    if (iType == 1) lblForth.Text = string.Format(dbo.GetLanguage(482), iReceiverId);// "正在采集接收器 "+iReceiverId+" 的数据 ... ";
                    else if (iType == 2) lblForth.Text = string.Format(dbo.GetLanguage(483), iReceiverId);// "正在将接收器 " + iReceiverId + " 的数据写入数据库 ... ";
                    else if (iType == 3) lblForth.Text = string.Format(dbo.GetLanguage(484), iReceiverId);// "接收器 " + iReceiverId + " 的数据采集完毕。 ";
                    else if (iType == 4) ShowGatherData();
                    break;

                case PC.WM_MeasureRefresh:
                    RefreshMeasure();
                    //GetParam();
                    break;

                case PC.WM_ResponseOrder:
                    if (fre != null && fre.Created)
                        fre.InitParam(false);
                    break;


                default:
                    base.DefWndProc(ref m);
                    break;
            }
        }


        #region 变量

        bool blClose = false;

        string sLastGatherNo = "";
        string sVariateSQL = "";
        string sOrderName = "";
        string sLastCOMID = "";

        bool blDataColumnChanged = false;
        bool blReceiverColumnChanged = false;
        string sServerIP = "";
        int iPort = 4001;

        IntPtr iHandle;
        Thread thread;

        SocketServer tcpServer;

        DataTable dtReceiver;
        DataTable dtGatherData;
        DataView dvGatherData;

        DataOrder ao;
        DatabaseObject dbo;
        FrmMonitor frmm;
        FrmReceiverEdit fre;
        private GSMModem Sms = new GSMModem();

        Hashtable htNetOrderList1 = new Hashtable();
        Hashtable htNetOrderList2 = new Hashtable();
        Hashtable htNetOrderList3 = new Hashtable();

        #endregion


        #region 加载事件

        private void FrmMain_Load(object sender, EventArgs e)
        {
            PublicFunc.GetVersion();//ref iVersion,ref iLVersion
            AmateParam.Configuration.Open();

            GSMModem.Instance = this.Sms;

            InitSource();
            GetParam();
            GetPort();

            foreach (ToolStripItem si in menuStrip1.Items)
            {
                ToolStripMenuItem mi = si as ToolStripMenuItem;
                if (mi == null || mi.Tag == null || mi.Tag.ToString() == "") continue;
                mi.Text = dbo.GetLanguage(mi.Tag);
            }
            gcIP.HeaderText = dbo.GetLanguage(147);
            gcGatherTime.HeaderText = dbo.GetLanguage(116);
            Column2.HeaderText = dbo.GetLanguage(339);
            gcOnline.HeaderText = dbo.GetLanguage(481);
            foreach (ToolStripItem si in contextMenuStrip1.Items)
            {
                ToolStripMenuItem mi = si as ToolStripMenuItem;
                if (mi == null || mi.Tag == null || mi.Tag.ToString() == "") continue;
                mi.Text = dbo.GetLanguage(mi.Tag);
            }
            foreach (ToolStripItem si in contextMenuStrip2.Items)
            {
                ToolStripMenuItem mi = si as ToolStripMenuItem;
                if (mi == null || mi.Tag == null || mi.Tag.ToString() == "") continue;
                mi.Text = dbo.GetLanguage(mi.Tag);
            }
        }

        private void FrmMain_Shown(object sender, EventArgs e)
        {
            if (dbo.dtMeasureType.Rows.Count == 0) return;

            //DataTable dtColumnParam = dbo.GetDataTableBySql("select * from ColumnParam where Name='ToolGatherData' order by FieldIndex", "ColumnParam");
            //if (dtColumnParam.Rows.Count > 0)
            //{
            //    foreach (DataRow dr in dtColumnParam.Rows)
            //    {
            //        string sFieldName = dr["FieldName"].ToString();
            //        //if (dgvGatherData.Columns.IndexOf(sFieldName) < 0) continue;
            //        if (sVariateSQL.IndexOf(sFieldName) > -1)
            //        {
            //            if (Convert.ToInt32(dr["FieldIndex"]) >= dgvGatherData.Columns.Count) return;
            //            if (dgvGatherData.Columns[sFieldName] != null)
            //            {
            //                dgvGatherData.Columns[sFieldName].DisplayIndex = Convert.ToInt32(dr["FieldIndex"]);
            //                dgvGatherData.Columns[sFieldName].Width = Convert.ToInt32(dr["FieldWidth"]);
            //            }
            //        }
            //    }
            //}

            //Lanch(true);

            tmWebset.Interval = 5 * 60 * 1000;
            tmWebset.Enabled = true;
            WebSms.GetBalance();
        }

        private void FrmMain_FormClosed(object sender, FormClosedEventArgs e)
        {
            Lanch(false);
        }

        private void FrmMain_FormClosing(object sender, FormClosingEventArgs e)
        {
            if ((blDataColumnChanged) && (dgvGatherData.Columns.Count > 0))
            {
                string sSQLInsert = "insert into ColumnParam(Name,FieldName,FieldIndex,FieldWidth) values('{0}','{1}',{2},{3});";
                string sSQL = "delete from ColumnParam where Name='ToolGatherData';";
                for (int i = 0; i < dgvGatherData.Columns.Count; i++)
                {
                    DataGridViewColumn dc = dgvGatherData.Columns[i];
                    if (dc.DataPropertyName.Trim() == "") continue;
                    sSQL = sSQL + string.Format(sSQLInsert, "ToolGatherData", dc.DataPropertyName, dc.DisplayIndex, dc.Width);
                }
                dbo.ExcuteSQL(sSQL);
            }
            if ((blReceiverColumnChanged) && (dgvReciver.Columns.Count > 0))
            {
                string sSQLInsert = "insert into ColumnParam(Name,FieldName,FieldIndex,FieldWidth) values('{0}','{1}',{2},{3});";
                string sSQL = "delete from ColumnParam where Name='ToolReciver';";
                for (int i = 0; i < dgvReciver.Columns.Count; i++)
                {
                    DataGridViewColumn dc = dgvReciver.Columns[i];
                    if (dc.DataPropertyName.Trim() == "") continue;
                    sSQL = sSQL + string.Format(sSQLInsert, "ToolReciver", dc.DataPropertyName, dc.DisplayIndex, dc.Width);
                }
                if (dbo != null) dbo.ExcuteSQL(sSQL);
            }

            if (!blClose)
            {
                e.Cancel = true;
                setFrmShow(false);
            }
        }

        private void FrmMain_Activated(object sender, EventArgs e)
        {
            //setFrmShow(true);
        }

        private void FrmMain_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Control && (e.KeyCode == Keys.F12))
            {
                m0DeBug_Click(null, null);
            }
        }

        private void FrmMain_Move(object sender, EventArgs e)
        {
            if (frmm != null && frmm.Created)
            {
                frmm.Location = new Point(this.Location.X - 300, this.Location.Y);
                frmm.BringToFront();
            }

        }

        private void tFrm_MouseEnter(object sender, EventArgs e)
        {
            ToolStripMenuItem tsm = sender as ToolStripMenuItem;
            if (tsm != null)
            {
                tsm.ForeColor = Color.Black;
            }
        }

        private void tFrm_MouseLeave(object sender, EventArgs e)
        {
            ToolStripMenuItem tsm = sender as ToolStripMenuItem;
            if (tsm != null)
            {
                tsm.ForeColor = Color.White;
            }
        }

        /// <summary>
        /// 获取端口信息
        /// </summary>
        private void GetPort()
        {
            sServerIP = AmateBussiness.GetSystemParamValue(dbo, "ListenIP ", "").ToString();
            iPort = Convert.ToInt32(AmateBussiness.GetSystemParamValue(dbo, "NetPort2", 4001));

            bool blHasIP = false;
            IPHostEntry ihe = Dns.GetHostByName(Dns.GetHostName());
            foreach (IPAddress ia in ihe.AddressList)
            {
                if (sServerIP == ia.ToString()) { blHasIP = true; break; }
            }
            if (!blHasIP)
            {
                FrmNetSet frm = new FrmNetSet(dbo);
                DialogResult dlr = frm.ShowDialog();
                if (dlr == DialogResult.Cancel) Close();
                sServerIP = frm.cbIP.Text;
            }
            Lanch(false);
            Lanch(true);

            lblFirst.ToolTipText = sServerIP + "," + iPort;

            Sms.Close();
            string sComPort = AmateBussiness.GetSystemParamValue(dbo, "SMS_ComPort", "COM3").ToString();
            int iBaudRate = PublicMethod.GetInt(AmateBussiness.GetSystemParamValue(dbo, "SMS_BaudRate", 9600));
            Sms.ComPort = sComPort;
            Sms.BaudRate = iBaudRate;

            #region  短信猫
            /*
            string sState = "";
            try
            {
                FormSms.mySms = new MySms(dbo);
                //Sms.Open();
                FormSms.StartSendThread();
                sState = "就绪";
            }
            catch (Exception ex)
            {
                sState = ex.Message + "Error";
            }
            SetNotifyIconTip("短信猫：", sState);
            */
            #endregion

        }

        /// <summary>
        /// 获取参数信息
        /// </summary>
        private void GetParam()
        {
            string sProductName = AmateBussiness.GetSystemParamValue(dbo, "ProductName_" + PublicFunc.sLanguage, dbo.GetLanguage(25)).ToString();//"阿米特无线温控管理系统"
            string sVersion = AmateBussiness.GetSystemParamValue(dbo, "Version ", "V3.0").ToString();
            notifyIcon1.Text = this.Text = sProductName + "_" + sVersion + "--" + dbo.GetLanguage(123);

            string sLanVer = AmateBussiness.GetSystemParamValue(dbo, "Language", "").ToString();
            if (sLanVer != PublicFunc.sLanguage) AmateBussiness.SetSystemParamValue(dbo, "Language", PublicFunc.sLanguage);

            //string s = ""; string s1 = "";
            //bool bl = AmateBussiness.GetSysTimer(dbo, ref s, ref s1);
            //if (!bl) this.Text = this.Text + "(" + dbo.GetLanguage(371) + ")";
            AmateBussiness.SetSystemParamValue(dbo, "ServerHandle", this.Handle.ToString());
        }

        /// <summary>
        /// 建立数据库连接
        /// </summary>
        private void InitSource()
        {
            dgvReciver.AutoGenerateColumns = false;
            dgvGatherData.AutoGenerateColumns = false;

            string sConn = PublicFunc.GetVersion();// frm.ShowDialog();
            if (sConn.StartsWith("Error"))
            {
                string sMes = (PublicFunc.sLanguage == "CN") ? "数据库连接配置文件出错，请重新配置！" : "Config file error,please re-config！";
                if (sMes != "") MessageBox.Show(sMes, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                Application.Exit();
            }
            dbo = new DatabaseObject(sConn);

            if (dbo.dtMeasureType.Rows.Count == 0)
            {
                MessageBox.Show(dbo.GetLanguage(42), dbo.GetLanguage(141), MessageBoxButtons.OK, MessageBoxIcon.Information);//"基础数据不完整,无法运行服务程序,请与管理员联系新增测量字段!");
                this.Close();
                return;
            }

            ao = new DataOrder(dbo);
            ao.frmHandle = iHandle = this.Handle;

            RefreshMeasure();
            RefreshReceiver();
        }


        private void m1AddRec_Click(object sender, EventArgs e)
        {
            fre = new FrmReceiverEdit(dbo, 0, null, ao.dtDeviceType);
            if (fre.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                RefreshReceiver();
                //AddReceiverOrder
            }
        }

        private void m1EditRec_Click(object sender, EventArgs e)
        {
            DataGridViewRow dgvr = dgvReciver.CurrentRow;
            if (dgvr != null)
            {
                DataRow drReceiver = (dgvr.DataBoundItem as DataRowView).Row;
                MyReceiver myReceiver = ao.htRecriver[drReceiver["KeyId"].ToString()];
                if (myReceiver == null) return;

                AddGetReceiverOrder(drReceiver);
                fre = new FrmReceiverEdit(dbo, 1, drReceiver, ao.dtDeviceType);
                if (fre.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    //RefreshReceiver();
                    AddSetReceiverOrder(drReceiver);
                }
            }
        }

        private void m1DeleteRec_Click(object sender, EventArgs e)
        {
            DataGridViewRow dgvr = dgvReciver.CurrentRow;
            if (dgvr != null)
            {
                DataRow drReceiver = (dgvr.DataBoundItem as DataRowView).Row;
                string sKeyId = drReceiver["KeyId"].ToString();
                MyReceiver myReceiver = ao.htRecriver[sKeyId];
                if (myReceiver != null && myReceiver.DeleteData())
                {
                    dtReceiver.Rows.Remove(drReceiver);
                    ao.htRecriver.Remove(sKeyId);
                }
            }
        }

        private void m0GetVersion_Click(object sender, EventArgs e)
        {
            //DataGridViewRow dgvr = dgvReciver.CurrentRow;
            //if (dgvr == null)
            //{
            //    MessageBox.Show(dbo.GetLanguage(221));//"请选择要查询版本的接收仪!"
            //    return;
            //}

            //if (GetUserType() != 0) return;

            DataGridViewSelectedRowCollection slDR = dgvReciver.SelectedRows;
            foreach (DataGridViewRow dgvr in slDR)
            {
                DataRow drReceiver = (dgvr.DataBoundItem as DataRowView).Row;
                AddOrder(drReceiver, "", null, "获取参数");
            }
            SendOrder();
        }

        private void m0Listen_Click(object sender, EventArgs e)
        {
            bool blListen = (m0Listen.Text == dbo.GetLanguage(292));//"停止监听");
            //m0Send.Enabled = blListen;
            Lanch(blListen);
        }

        private void m0GatherSelected_Click(object sender, EventArgs e)
        {
            SendOrder(false, "GatherData");
        }

        private void m0SetParam_Click(object sender, EventArgs e)
        {
            FrmNetSet frm = new FrmNetSet(dbo);
            DialogResult dr = frm.ShowDialog();
            if (dr == DialogResult.OK)
            {
                GetPort();
            }
        }

        private void m0DeBug_Click(object sender, EventArgs e)
        {
            if (frmm == null || !frmm.Created)
            {
                frmm = new FrmMonitor(tcpServer.SendOrder, ao, dgvReciver);
                frmm.Location = new Point(this.Location.X - 300, this.Location.Y);
                frmm.Show();
            }
            else
            {
                frmm.BringToFront();
            }
        }

        private void m0ClearData_Click(object sender, EventArgs e)
        {
            if (dtGatherData != null)
            {
                dtGatherData.Clear();
                dtGatherData.AcceptChanges();
            }
        }

        private void m0SetDateTime_Click(object sender, EventArgs e)
        {
            DataGridViewRow dgvr = dgvReciver.CurrentRow;
            if (dgvr == null)
            {
                MessageBox.Show(dbo.GetLanguage(218), dbo.GetLanguage(141), MessageBoxButtons.OK, MessageBoxIcon.Information);//"请选择要设置时钟的接收仪!"
                return;
            }

            //if (GetUserType() != 0) return;
            DataRow dr = (dgvr.DataBoundItem as DataRowView).Row;
            string sDate = DateTime.Now.ToUniversalTime().ToString("yyMMddHHmmss");
            string[] sOrder = new string[6];
            for (int i = 0; i < sDate.Length; i += 2)
            {
                sOrder[i / 2] = Convert.ToInt32(sDate.Substring(i, 2)).ToString("X2");
            }
            AddOrder(dr, "01", sOrder, "设置时钟");
            SendOrder();
        }

        private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            if (!this.Visible) this.Show();
        }

        private void notifyIcon1_MouseClick(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                setFrmShow(!this.Visible);
            }
        }

        private void 关于ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            FrmProductInfo fpi = new FrmProductInfo(dbo, 0);
            fpi.ShowDialog(this);
        }

        private void 刷新设备ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            RefreshReceiver();
        }

        private void 短信监控ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            FormSms fs = new FormSms(dbo);
            fs.ShowDialog();
        }

        private void 退出ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            blClose = true;
            Close();
        }

        private void 注册传感器ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            DataGridViewSelectedRowCollection slDR = dgvReciver.SelectedRows;
            foreach (DataGridViewRow dgvr in slDR)
            {
                DataRow drReceiver = (dgvr.DataBoundItem as DataRowView).Row;
                MyReceiver myReceiver = ao.htRecriver[drReceiver["KeyId"].ToString()];
                if (myReceiver == null) return;
                AddOrder(drReceiver, "02", myReceiver.GetSensor(1), "注册传感器");
            }
            SendOrder();
        }

        private void m1GatherSelected_Click(object sender, EventArgs e)
        {
            DataGridViewSelectedRowCollection slDR = dgvReciver.SelectedRows;
            foreach (DataGridViewRow dgvr in slDR)
            {
                DataRow drReceiver = (dgvr.DataBoundItem as DataRowView).Row;
                AddOrder(drReceiver, "", null, "历史数据");
            }
            SendOrder();
        }

        private void m1SetSendCycle_Click(object sender, EventArgs e)
        {
            DataGridViewSelectedRowCollection slDR = dgvReciver.SelectedRows;
            foreach (DataGridViewRow dgvr in slDR)
            {
                DataRow drReceiver = (dgvr.DataBoundItem as DataRowView).Row;
                MyReceiver myReceiver = ao.htRecriver[drReceiver["KeyId"].ToString()];
                if (myReceiver == null) return;
                AddOrder(drReceiver, "01", myReceiver.GetCycle(), "设置周期");

                //string[] SendCycles = new string[] { drReceiver["SendCycle"].ToString() };
                //AddOrder(drReceiver, "01", SendCycles, "设置周期");
            }
            SendOrder();
        }

        private void m1SetWarnLine_Click(object sender, EventArgs e)
        {
            DataGridViewSelectedRowCollection slDR = dgvReciver.SelectedRows;
            foreach (DataGridViewRow dgvr in slDR)
            {
                DataRow drReceiver = (dgvr.DataBoundItem as DataRowView).Row;
                MyReceiver myReceiver = ao.htRecriver[drReceiver["KeyId"].ToString()];
                if (myReceiver == null) return;

                bool IsImmediateAlarm = true;
                bool.TryParse(drReceiver["IsImmediateAlarm"].ToString(), out IsImmediateAlarm);
                string flag = "00" + ((IsImmediateAlarm) ? "83" : "80");//flag
                AddOrder(drReceiver, flag, myReceiver.GetThreshold(IsImmediateAlarm), "设置阀值");

                //DataRow drReceiver = (dgvr.DataBoundItem as DataRowView).Row;
                //DataRow[] drMs = dbo.dtMeasureType.Select("Mode = 1");
                //int iC = drMs.Length;
                //string[] WarnLines = new string[iC * 2];
                //for (int i = 0; i < iC; i++)
                //{
                //    string sM = (((i + 1) % 2 == 0) ? "U" : "L") + drMs[i]["ID"].ToString();
                //    if (dtReceiver.Columns.Contains(sM)) WarnLines[i] = drReceiver[sM].ToString();
                //}
                //AddOrder(drReceiver, "", WarnLines, "设置阀值");
            }
            SendOrder();

        }

        private void m1Reboot_Click(object sender, EventArgs e)
        {
            DataGridViewSelectedRowCollection slDR = dgvReciver.SelectedRows;
            foreach (DataGridViewRow dgvr in slDR)
            {
                DataRow drReceiver = (dgvr.DataBoundItem as DataRowView).Row;
                AddOrder(drReceiver, "", null, "重启设备");
            }
            SendOrder();
        }

        private void lblForth_Click(object sender, EventArgs e)
        {

        }

        private void dgvReciver_ColumnDisplayIndexChanged(object sender, DataGridViewColumnEventArgs e)
        {
            blReceiverColumnChanged = true;

        }

        private void dgvReciver_ColumnWidthChanged(object sender, DataGridViewColumnEventArgs e)
        {
            blReceiverColumnChanged = true;
        }

        private void dgvSensor_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)
        {
            if (dgvReciver.CurrentRow == null) return;

            if (e.Button == MouseButtons.Right && sender is DataGridView)
            {
                BuildColumn.dgv_CellMouseDown(sender, e);
            }
            else
            {
                //DataRow dr = (dgvReciver.CurrentRow.DataBoundItem as DataRowView).Row;
                //toolTip1.SetToolTip(dgvReciver, dr["Phone"].ToString());
            }
        }

        private void dgvReciver_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
        {
            lblSecond.Text = dbo.GetLanguage(311) + dtReceiver.Rows.Count + dbo.GetLanguage(415);//" 个接收器";"共有 " 
        }

        private void dgvGatherData_ColumnWidthChanged(object sender, DataGridViewColumnEventArgs e)
        {
            blDataColumnChanged = true;
        }

        private void dgvGatherData_ColumnDisplayIndexChanged(object sender, DataGridViewColumnEventArgs e)
        {
            blDataColumnChanged = true;
        }

        private void dgv_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
        {
            string sStaut = dbo.GetLanguage(195);
            int iCountOK = 0;
            foreach (DataGridViewRow dvr in dgvReciver.Rows)
            {
                DataRow dr = (dvr.DataBoundItem as DataRowView).Row;

                if (dr["Online"].ToString() != sStaut) dvr.DefaultCellStyle.BackColor = System.Drawing.Color.LightGray;
                else
                {
                    dvr.DefaultCellStyle.BackColor = System.Drawing.Color.White;
                    iCountOK++;
                }
            }
            lblSecond.ToolTipText = dbo.GetLanguage(311) + iCountOK + dbo.GetLanguage(415) + sStaut;
        }

        private void dgvGatherData_ColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            if (dgvGatherData.Columns[e.ColumnIndex].HeaderText == dbo.GetLanguage(263))//"传感器"
            {
                if (sOrderName == "")
                {
                    if (dvGatherData == null) return;
                    dvGatherData.Sort = "ReceiverId,SensorID desc";
                    sOrderName = "desc";
                }
                else
                {
                    dvGatherData.Sort = "ReceiverId,SensorID";
                    sOrderName = "";
                }
            }
        }


        //private bool CheckUserType()
        //{
        //    string strUsersType = dbo.drLoginUser["UserType"].ToString();
        //    if (strUsersType != "0")
        //    {
        //        MessageBox.Show(dbo.GetLanguage(188), dbo.GetLanguage(141), MessageBoxButtons.OK, MessageBoxIcon.Information);
        //        return false;//"未分配权限,请与管理员联系!", "提示",
        //    }
        //    return true;
        //}

        //private int GetUserType()
        //{
        //    FrmUserCheck frm = new FrmUserCheck(dbo);
        //    frm.ShowDialog();
        //    return frm.iUserType;
        //}

        private void setFrmShow(bool bShow)
        {
            if (this.Visible != bShow)
            {
                this.Visible = bShow;
                if (bShow) this.BringToFront();
            }
            if (frmm != null && frmm.Created)
            {
                frmm.Visible = bShow;
                if (bShow) frmm.BringToFront();
            }
        }

        #endregion


        #region 数据发送处理函数

        /// <summary>
        /// 定时队列发送数据
        /// </summary>
        private void SendOrder()
        {
            if (htNetOrderList1.Count > 0 || htNetOrderList2.Count > 0 || htNetOrderList3.Count > 0) SendToNet(6000);
        }

        /// <summary>
        /// 定时队列发送网口数据
        /// </summary>
        /// <param name="iSleep"></param>
        private void SendToNet(int iSleep)
        {
            tmRecSend.Enabled = false;

            Thread.Sleep(iSleep);
            if (htNetOrderList1.Count > 0)
            {
                foreach (DictionaryEntry de in htNetOrderList1)
                {
                    string[] sOrder = de.Key.ToString().Split('*');
                    string sIP = sOrder[0];
                    string sKeyId = sOrder[1];
                    byte[] Hex = (byte[])de.Value;
                    sLastCOMID = de.Key.ToString().Trim();
                    lblForth.Text = GetInstanceInfo(sKeyId, 1, Hex);
                    tcpServer.SendOrder(sIP, Hex);
                    htNetOrderList1.Remove(de.Key);
                    tmRecSend.Enabled = true;
                    return;
                }
            }
            if (htNetOrderList2.Count > 0)
            {
                foreach (DictionaryEntry de in htNetOrderList2)
                {
                    string[] sOrder = de.Key.ToString().Split('*');
                    string sIP = sOrder[0];
                    string sKeyId = sOrder[1];
                    byte[] Hex = (byte[])de.Value;
                    sLastCOMID = de.Key.ToString().Trim();
                    lblForth.Text = GetInstanceInfo(sKeyId, 2, Hex);
                    tcpServer.SendOrder(sIP, Hex);
                    htNetOrderList2.Remove(de.Key);
                    tmRecSend.Enabled = true;
                    return;
                }
            }
            if (htNetOrderList3.Count > 0)
            {
                foreach (DictionaryEntry de in htNetOrderList3)
                {
                    string[] sOrder = de.Key.ToString().Split('*');
                    string sIP = sOrder[0];
                    string sKeyId = sOrder[1];
                    byte[] Hex = (byte[])de.Value;
                    sLastCOMID = de.Key.ToString().Trim();
                    lblForth.Text = GetInstanceInfo(sKeyId, 3, Hex);
                    tcpServer.SendOrder(sIP, Hex);
                    htNetOrderList3.Remove(de.Key);
                    tmRecSend.Enabled = true;
                    return;
                }
            }
            else
            {
                tmRecSend.Enabled = true;
            }

            //if (iNormalSendCycle > 5)
            //{
            //    tmGatherMData.Enabled = true;
            //    ao.blDataFromModbus = true;
            //}

            //ResetGatherDate();
            //tmGatherAData.Enabled = true;
            //htNetOrderList.Clear();
        }

        /// <summary>
        /// 主动采集数据
        /// </summary>
        /// <param name="blAll"></param>
        /// <param name="sOrderName"></param>
        private void SendOrder(bool blAll, string sOrderName)
        {
            SetMainLbl(dbo.GetLanguage(27));//"正在采集数据 ... ";

            ClearNETrder();

            ao.sGatherNo = PublicFunc.GetUniformDateString(DateTime.Now);
            ao.blDataFromCall = true;

            string sSQL = "";
            try
            {
                if (blAll)
                {
                    DataView dv = new DataView(dtReceiver);
                    dv.Sort = "ReceiverId";
                    //foreach (DataRow dr in dtReceiver.Rows)
                    for (int i = 0; i < dv.Count; i++)
                    {
                        DataRow drReceiver = dv[i].Row;
                        drReceiver["Online"] = dbo.GetLanguage(192);// "离线";
                        AddOrder(drReceiver, "0001", null, sOrderName);
                    }
                    sSQL = "update SensorXY set X=null,Y=null," + string.Format(PublicFunc.dbo_Measure, "Last", "=null") + ",W='" + PublicFunc.dbo_W + "';";
                }
                else
                {
                    DataGridViewSelectedRowCollection slDR = dgvReciver.SelectedRows;
                    foreach (DataGridViewRow dgvr in slDR)
                    {
                        DataRow drReceiver = (dgvr.DataBoundItem as DataRowView).Row;
                        AddOrder(drReceiver, "0001", null, sOrderName);
                        sSQL = sSQL + "update SensorXY set X=null,Y=null," + string.Format(PublicFunc.dbo_Measure, "Last", "=null") + " where ID like '" + drReceiver["ReceiverId"].ToString() + "-%';update SensorXY set W='" + PublicFunc.dbo_W + "';";
                        drReceiver["Online"] = dbo.GetLanguage(192);//离线
                    }
                }
                if (sSQL != "") dbo.ExcuteSQL(sSQL);
                SendOrder();
            }
            catch (Exception em)
            {
                ClearNETrder();
                ao.blDataFromCall = false;
                SetMainLbl(em.Message);
            }
        }

        /// <summary>
        /// 采集命令生成
        /// </summary>
        /// <param name="dr"></param>
        /// <param name="sFlag"></param>
        /// <param name="sValues"></param>
        /// <param name="sOrderName"></param>
        private void AddOrder(DataRow dr, string sFlag, string[] sValues, string sOrderName)
        {
            string sOrder = "";
            if (dr == null)
            {
                byte[] byteHex = ao.GetOrder(sOrderName, "", "", sValues, ref sOrder);//cbOrder.SelectedValue.ToString()cbOrder.SelectedValue.ToString(), 
                sOrder = sOrder.Trim();
                if (!htNetOrderList1.ContainsKey("000*" + sOrder)) htNetOrderList1.Add("000*" + sOrder, byteHex);
            }
            else
            {
                string sReceiverKeyId = dr["KeyId"].ToString();
                byte[] byteHex = ao.GetOrder(sOrderName, sReceiverKeyId, sFlag, sValues, ref sOrder);
                if (byteHex == null) return;
                sOrder = sOrder.Trim();
                if (dr["Port"].ToString().Trim() != "")
                {
                    string sKey = dr["Port"].ToString() + "*" + dr["KeyId"].ToString() + "*" + sOrder;//dr["Port"].ToString() + "*" + sOrder;

                    if (!htNetOrderList1.ContainsKey(sKey)) htNetOrderList1.Add(sKey, byteHex);
                    if (sOrder.StartsWith("68 55"))
                    {
                        if (!htNetOrderList2.ContainsKey(sKey)) htNetOrderList2.Add(sKey, byteHex);
                        if (!htNetOrderList3.ContainsKey(sKey)) htNetOrderList3.Add(sKey, byteHex);
                    }
                }
            }
        }

        /// <summary>
        /// 获取接收器参数命令
        /// </summary>
        /// <param name="dr"></param>
        private void AddGetReceiverOrder(DataRow dr)
        {
            string[] sOrder = new string[0];

            AddOrder(dr, "00", sOrder, "读取参数");
            AddOrder(dr, "00", sOrder, "注册传感器");
            AddOrder(dr, "00", sOrder, "设置周期");
            AddOrder(dr, "00", sOrder, "设置时钟");
            AddOrder(dr, "00", sOrder, "设置阀值");

            SendOrder();
        }

        /// <summary>
        /// 设置接收器完成后生成发送设置命令
        /// </summary>
        /// <param name="dr"></param>
        private void AddSetReceiverOrder(DataRow dr)
        {
            ClearNETrder();

            MyReceiver myReceiver = ao.htRecriver[dr["KeyId"].ToString()];
            if (myReceiver == null) return;

            myReceiver.RefreshParam(dr);

            AddOrder(dr, "02", myReceiver.GetSensor(1), "注册传感器");
            AddOrder(dr, "01", myReceiver.GetCycle(), "设置周期");

            bool IsImmediateAlarm = true;
            bool.TryParse(dr["IsImmediateAlarm"].ToString(), out IsImmediateAlarm);
            string flag = "00" + ((IsImmediateAlarm) ? "83" : "80");//flag
            AddOrder(dr, flag, myReceiver.GetThreshold(IsImmediateAlarm), "设置阀值");

            AddOrder(dr, "01", myReceiver.GetDateTime(), "设置时钟");

            SendOrder();

            dbo.ExcuteSQL("Update Sys_Receiver set IsUpdate='False' where IsUpdate='True' and KeyId=" + myReceiver.iReceiverKeyID);
        }

        #endregion


        #region 数据接收处理函数
        /// <summary>
        /// 清除网口发生缓冲区
        /// </summary>
        private void ClearNETrder()
        {
            //blCOMReturn = false;
            sLastCOMID = "";
            //sLastReceiverId = "";
            htNetOrderList1.Clear();
            htNetOrderList2.Clear();
            htNetOrderList3.Clear();
        }

        /// <summary>
        /// 设置底栏文本
        /// </summary>
        /// <param name="sText"></param>
        private void SetMainLbl(string sText)
        {
            lock (lblForth)
            {
                if (sText != "")
                {
                    lblForth.Text = sText;
                }
            }
        }

        /// <summary>
        /// 设置监听板数据
        /// </summary>
        /// <param name="sIP"></param>
        /// <param name="byteData"></param>
        /// <param name="iType"></param>
        private void SetMonitor(string sIP, byte[] byteData, int iType)
        {
            if (frmm != null && frmm.Created)
            {
                frmm.AddData(sIP, byteData, iType);
            }
        }

        /// <summary>
        /// 设置任务栏气泡提示
        /// </summary>
        /// <param name="sTitle"></param>
        /// <param name="sText"></param>
        private void SetNotifyIconTip(string sTitle, string sText)
        {
            if (sText != "")
            {
                if (sText.EndsWith("Error"))
                {
                    sText = sText.TrimEnd("Error".ToCharArray());
                    notifyIcon1.ShowBalloonTip(5000, sTitle, sText, ToolTipIcon.Info);
                }
                else sText = sText.TrimEnd("OK".ToCharArray());
                SetMainLbl(sTitle + ":" + sText);
            }
        }

        private void ShowGatherData()
        {
            tmWarn.Enabled = false;//.Stop();
            tmWarn.Enabled = true; //Start();stri
        }

        /// <summary>
        /// 监听启动器
        /// </summary>
        /// <param name="bl"></param>
        private void Lanch(bool bl)
        {
            LanuchNet(bl);
            if (!bl)
            {
                foreach (DataRow dr in dtReceiver.Rows)
                {
                    if (dr["Online"].ToString() == dbo.GetLanguage(195)) dr["Online"] = dbo.GetLanguage(192);// "离线"; //"在线"
                }
            }
        }

        /// <summary>
        /// 网口监听启动器
        /// </summary>
        /// <param name="blListen"></param>
        private void LanuchNet(bool blListen)
        {
            if (blListen)
            {
                if (tcpServer == null)
                {
                    tcpServer = new SocketServer(ao);
                    tcpServer.setNotifyIconTip = SetNotifyIconTip;
                    tcpServer.setMonitor = SetMonitor;
                    ao.netSend = tcpServer.SendOrder;
                }
                tcpServer.SetParam(sServerIP, iPort, 5000);
                thread = new Thread(new ThreadStart(tcpServer.CreateServer));
                thread.Start();
                m0Listen.Text = dbo.GetLanguage(298);// "停止监听";
                lblFirst.Text = dbo.GetLanguage(293);//"状态:正在监听 ... ";
            }
            else
            {
                if (tcpServer != null)
                {
                    tcpServer.StopListener();
                    //tcpServer = null;
                }
                m0Listen.Text = dbo.GetLanguage(292);// "开始监听";
                lblFirst.Text = dbo.GetLanguage(294);//"状态:监听已经停止";
            }
            tmPing.Enabled = blListen;
        }

        private void SetStatusInfo()
        {
            //if (dgvGatherData.DataSource == null) return;
            //DataView dv = (DataView)dgvGatherData.DataSource;
            //DataTable dt = dv.Table;
            //string sInfo = dbo.GetLanguage(247) + dt.Rows.Count;//"记录数:"
            //string sAvg = ""; int iIndex = 0;
            //foreach (DataRow dr in dtMeasureType.Rows)
            //{
            //object o = dt.Compute("max(T)", "");
            //if (o != DBNull.Value)
            //{
            //    sInfo = sInfo + ";" + dbo.GetLanguage(378) + ":" + o.ToString();// 最高温度
            //    o = dt.Compute("min(T)", "");
            //    sInfo = sInfo + "/" + dbo.GetLanguage(379) + ":" + o.ToString();//最低温度
            //    o = dt.Compute("avg(T)", "");
            //    sAvg = o.ToString(); iIndex = sAvg.IndexOf(".");
            //    if ((iIndex > -1) && (sAvg.Length > (iIndex + 2))) sAvg = sAvg.Substring(0, iIndex + 2);
            //    sInfo = sInfo + "/" + dbo.GetLanguage(380) + ":" + sAvg;//平均温度
            //}

            //o = dt.Compute("max(H)", "");
            //if (o != DBNull.Value)
            //{

            //    sInfo = sInfo + " ; " + dbo.GetLanguage(381) + ":" + o.ToString();//最高湿度
            //    o = dt.Compute("min(H)", "");
            //    sInfo = sInfo + "/" + dbo.GetLanguage(382) + ":" + o.ToString();//最低湿度
            //    o = dt.Compute("avg(H)", "");
            //    sAvg = o.ToString(); iIndex = sAvg.IndexOf(".");
            //    if ((iIndex > -1) && (sAvg.Length > (iIndex + 2))) sAvg = sAvg.Substring(0, iIndex + 2);
            //    sInfo = sInfo + "/" + dbo.GetLanguage(383) + ":" + sAvg;//平均湿度
            //}
            //}
            string str = AmateBussiness.GetDataAvgValue(dbo, dtGatherData, 0);
            if (str == "") str = dbo.GetLanguage(64);
            lblForth.Text = lblForth.ToolTipText = str;
        }

        /// <summary>
        /// 获取命令发送状态文本
        /// </summary>
        /// <param name="sReceiverId"></param>
        /// <param name="iIndex"></param>
        /// <param name="byteHex"></param>
        /// <returns></returns>
        private string GetInstanceInfo(string sReceiverId, int iIndex, byte[] byteHex)
        {
            string sRet = "";
            string sHead = byteHex[0].ToString("X2") + byteHex[1].ToString("X2");
            switch (sHead)
            {
                case "6855":
                    if (iIndex == 1)
                        sRet = string.Format(dbo.GetLanguage(487), sReceiverId) + "," + dbo.GetLanguage(343);// "正在采集接收仪 " + sReceiverId + " 数据,等待数据返回 ... ";
                    else
                        sRet = string.Format(dbo.GetLanguage(324), iIndex) + string.Format(dbo.GetLanguage(4), sReceiverId) + "," + dbo.GetLanguage(343);//"正在第 " " 次采集接收仪 "" 数据,等待数据返回 ... ";
                    break;
                case "6866":
                    break;
                case "6A1F":
                    if (iIndex == 1)
                        sRet = string.Format("正在匹配接收仪{0}", sReceiverId) + "," + dbo.GetLanguage(343);
                    else
                        sRet = string.Format(dbo.GetLanguage(324), iIndex) + string.Format("匹配接收仪{0}", sReceiverId) + "," + dbo.GetLanguage(343);
                    break;
                case "6A20":
                    if (iIndex == 1)
                        sRet = dbo.GetLanguage(494) + sReceiverId + dbo.GetLanguage(491) + "," + dbo.GetLanguage(343);//" 时间,等待数据返回 ... ";"正在设置接收仪 " 
                    else
                        sRet = dbo.GetLanguage(324) + iIndex + dbo.GetLanguage(490) + sReceiverId + dbo.GetLanguage(491) + "," + dbo.GetLanguage(343);//" 时间,等待数据返回 ... ";"正在第 " " 次设置接收仪 " 
                    break;
                case "6A21":
                    if (iIndex == 1)
                        sRet = dbo.GetLanguage(488) + sReceiverId + dbo.GetLanguage(56) + "," + dbo.GetLanguage(343);//" 软件版本号,等待数据返回 ... ";"正在查询接收仪 " 
                    else
                        sRet = dbo.GetLanguage(324) + iIndex + dbo.GetLanguage(489) + sReceiverId + dbo.GetLanguage(56) + "," + dbo.GetLanguage(343);//" "正在第 " 次查询接收仪 " " 软件版本号,等待数据返回 ... ";
                    break;
                case "6A22":
                    break;
                case "6A23":
                    if (iIndex == 1)
                        sRet = dbo.GetLanguage(494) + sReceiverId + dbo.GetLanguage(3) + "," + dbo.GetLanguage(343);//" 采集周期,等待数据返回 ... ";"正在设置接收仪 "
                    else
                        sRet = dbo.GetLanguage(324) + iIndex + dbo.GetLanguage(490) + sReceiverId + dbo.GetLanguage(3) + "," + dbo.GetLanguage(343);//"正在第 "" 次设置接收仪 "" 采集周期,等待数据返回 ... ";
                    break;
                case "6A24":
                    if (iIndex == 1)
                        sRet = dbo.GetLanguage(494) + sReceiverId + dbo.GetLanguage(492) + "," + dbo.GetLanguage(343);// " 报警门限,等待数据返回 ... ";"正在设置接收仪 " 
                    else
                        sRet = dbo.GetLanguage(324) + iIndex + dbo.GetLanguage(490) + sReceiverId + dbo.GetLanguage(492) + "," + dbo.GetLanguage(343);//"正在第 "" 次设置接收仪 " " 报警门限,等待数据返回 ... ";
                    break;
                case "6A25":
                    if (iIndex == 1)
                        sRet = string.Format("正在重启接收仪{0}", sReceiverId);
                    else
                        sRet = string.Format(dbo.GetLanguage(324), iIndex) + string.Format("重启接收仪{0}", sReceiverId) + "," + dbo.GetLanguage(343);
                    break;
                default:
                    sRet = dbo.GetLanguage(326);
                    break;

            }
            return sRet;
        }

        private DataTable GetGatherData(string sGatherNo)
        {
            DataTable dtGatherData = null;
            sLastGatherNo = sGatherNo;
            foreach (System.Collections.Generic.KeyValuePair<string, MyReceiver> kv in ao.htRecriver)
            {
                if (!kv.Value.isConnected) continue;
                DataTable dt = kv.Value.dtGatherData;
                if (dt != null && dt.Rows.Count > 0)
                {
                    if (dtGatherData == null) dtGatherData = dt;
                    else if (dt != null) dtGatherData.Merge(dt);
                }
            }
            //dgvGatherData.DataSource = dtGatherData;
            dvGatherData = new DataView(dtGatherData);
            dgvGatherData.DataSource = dvGatherData;
            return dtGatherData;
        }

        /// <summary>
        /// 刷新接收器数据
        /// </summary>
        private void RefreshReceiver()
        {
            ao.htRecriver.Clear();
            dtReceiver = dbo.GetDataTableBySql("Select a.*,b.UPARA_1,b.LPARA_1,b.UPARA_2,b.LPARA_2,'" + dbo.GetLanguage(192) + "' [Online] ,'' GatherFrequency " +
                                               "From Sys_Receiver a LEFT JOIN Sys_Receiver_Threshold b ON a.KeyId=b.KeyId Where a.DeviceType>=33 order by a.KeyId ", "Receiver");//CreateReceiverTable();
            foreach (DataRow dr in dtReceiver.Rows)
            {
                string sReceiverKeyId = dr["KeyId"].ToString();
                if (!ao.htRecriver.ContainsKey(sReceiverKeyId)) ao.htRecriver.Add(sReceiverKeyId, new MyReceiver(dbo, dr));
            }
            dtReceiver.PrimaryKey = new DataColumn[] { dtReceiver.Columns["KeyId"] };
            DataView dvReceiver = new DataView(dtReceiver);
            ao.dtReceiver = dtReceiver;
            dvReceiver.Sort = "KeyId";
            dgvReciver.DataSource = dvReceiver;
        }

        /// <summary>
        /// 刷新测量参数
        /// </summary>
        private void RefreshMeasure()
        {
            dbo.RefreshMeasureType();
            sVariateSQL = BuildColumn.CreateGatherColumn(dbo, dgvGatherData);
            //Hashtable htMeasureType = new System.Collections.Hashtable();
            //foreach (DataRow dr in dbo.dtMeasureType.Rows)
            //{
            //    htMeasureType.Add(Convert.ToInt32(dr["Tag"]), dr["ID"].ToString());
            //}
            //ao.htMeasureType = htMeasureType;
        }

        #endregion


        #region 计时器

        private void tmPing_Tick(object sender, EventArgs e)
        {
            foreach (DataGridViewRow dvr in dgvReciver.Rows)
            {
                DataRow dr = (dvr.DataBoundItem as DataRowView).Row;
                //tcpServer.SendOrder(dr["Port"].ToString(), ao.GetOrderReceiver("AAAA" + dr["ReceiverID"], 0)); Convert.ToInt32(dr["SendCycle"])
                if (AmateBussiness.isDorp(dr["GatherFrequency"].ToString(), 5)) dr["Online"] = dbo.GetLanguage(195);
                else
                {
                    dr["Online"] = dbo.GetLanguage(192);
                    ao.CleanRecedRecord(dr["Port"].ToString());
                }
            }

            //tmPing.Enabled = false;
            //threadPing = new Thread(new ThreadStart(probeReceiver.SendPing));
            //threadPing.Start();
        }

        private void tmWait_Tick(object sender, EventArgs e)
        {
            tmWait.Enabled = false;
            SendOrder();
        }

        private void tmWebset_Tick(object sender, EventArgs e)
        {
            //DataTable dt = dbo.GetDataTableBySql("Select *,'' Online,'' GatherFrequency From Sys_Receiver Where IsUpdate='True'", "IsUpdate");
            //if (dt.Rows.Count > 0)
            //{
            //    foreach (DataRow dr in dt.Rows)
            //    {
            //        AddSetReceiverOrder(dr);
            //    }
            //}
            //bool bRefreshReport = DateTime.Now.Hour == 2 && DateTime.Now.Minute <= 30;
            //foreach (MyReceiver myRec in ao.htRecriver.Values)
            //{
            //    if (bRefreshReport) myRec.RefreshDayReport(); //执行报表更新
            //}
        }

        /// <summary>
        /// 前端操作响应定时器
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tmWarn_Tick(object sender, EventArgs e)
        {
            if (htNetOrderList1.Count == 0 && htNetOrderList2.Count == 0 && htNetOrderList3.Count == 0)
            {
                tmWarn.Enabled = false;
                //lblForth.Text = dbo.GetLanguage(26); this.Refresh();// "正在搜集报警数据 ... "; 
                GetGatherData(ao.sGatherNo);
                //if (ao.blDataFromCall)
                //{
                //    ao.blDataFromCall = false;
                //    dbo.ExcuteSQL("insert into GatherNo(GatherNo) values('" + sGatherNo + "');update SystemParam set Value='" + sGatherNo + "' where Name='LastGatherNo';");
                //    RefreshReceiverHardware();
                //    //SetNoGatherData();
                //}
                //else
                //{
                //    dbo.ExcuteSQL("update SystemParam set Value='" + sGatherNo + "' where Name='LastGatherNo';");
                //}
                //RefreshManagerData();
                SetStatusInfo();
            }
        }

        private void tmRecSend_Tick(object sender, EventArgs e)
        {
            if (htNetOrderList1.Count == 0 && htNetOrderList2.Count == 0 && htNetOrderList3.Count == 0)
            {
                tmRecSend.Enabled = false;

                if (!ao.blDataFromCall)
                {
                    DataView dv = new DataView(dtReceiver);
                    dv.Sort = "Online";
                    string sReceiver = "";
                    foreach (DataRowView drv in dv.FindRows(dbo.GetLanguage(192)))
                    {
                        sReceiver += drv["KeyId"] + "、";
                    }
                    if (sReceiver.TrimEnd('、') != "" && !ao.blDataFromCall)
                    {
                        notifyIcon1.ShowBalloonTip(5000, dbo.GetLanguage(441), sReceiver.TrimEnd('、'), ToolTipIcon.Warning);
                    }
                }
                SetMainLbl(dbo.GetLanguage(64));// "命令执行完毕！";
            }
            else
            {
                SendOrder();
            }
        }

        #endregion

    }
}
